package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDTO dto) {
        String password = dto.getPassword();
        String phone = dto.getPhone();
        if (StringUtils.isNoneBlank(password) && StringUtils.isNoneBlank(phone)) {
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone));
            if (apUser == null) {
                CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            String mdPassword = DigestUtils.md5DigestAsHex((password + apUser.getSalt()).getBytes());
            if (!apUser.getPassword().equals(mdPassword)) {
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            if (apUser.getStatus()) {
                CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
            }
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            apUser.setPassword("");
            apUser.setSalt("");
            Map map = new HashMap<>();
            map.put("token",token);
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        } else {
            if (dto.getEquipmentId() == null) {
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
            }
            String token = AppJwtUtil.getToken(0L);
            Map map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
